import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui';
import 'package:path_provider/path_provider.dart';

class Widget_RepaintBoundary_Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return Widget_RepaintBoundary_State();
  }
}

class Widget_RepaintBoundary_State extends State<Widget_RepaintBoundary_Page> {
  GlobalKey globalKey = new GlobalKey();

  Future<File> _capture() async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext
          .findRenderObject();
      //boundary.toImage()转化为ui.Image对象,不会自动为包裹的组件添加背景，不设置可能会缺失背景
      var image = await boundary.toImage(pixelRatio: window.devicePixelRatio);
      //将image转化为byteData
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      //这个对象就是图片数据
      Uint8List pngBytes = byteData.buffer.asUint8List();

      String sTempDir = (await getTemporaryDirectory()).path;
      bool isDirExist = await Directory(sTempDir).exists();
      if (!isDirExist) {
        Directory(sTempDir).create();
      }

      Future<File> file = File(sTempDir + "/abc.png").writeAsBytes(pngBytes);


      return file;

    } catch (e) {
      print(e);
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    var file = "/data/user/0/com.yourcompany.test1/cache/abc.png";
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text("RepaintBoundary"),
          ),
          body: Column(
            children: <Widget>[
              RepaintBoundary(
                key: globalKey,
                child: Text("RepaintBoundary组件"),
              ),
              RaisedButton(
                  onPressed: () {
                    _capture().then((_file){
                      setState(() {
                        debugPrint(_file.path);
                        file = _file.path;
                      });
                    }).whenComplete((){

                    });
                  }
              ),
              Image.asset(file),
            ],
          )
      ),
    );
  }
}
/**
 * const RepaintBoundary({ Key key, Widget child })
 */
